package com.jinghang.wayofrich.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.*;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.jinghang.wayofrich.MainActivity;
import com.jinghang.wayofrich.R;
import com.jinghang.wayofrich.activity.ApplyCardActivity;
import com.jinghang.wayofrich.activity.BecomeVipActivity;
import com.jinghang.wayofrich.activity.InviteCardActivity;
import com.jinghang.wayofrich.activity.InviteVipActivity;
import com.jinghang.wayofrich.adapter.IndexListAdapter;
import com.jinghang.wayofrich.beans.IndexArticle;
import com.jinghang.wayofrich.beans.IndexBank;
import com.jinghang.wayofrich.adapter.IndexGridAdapter;
import com.jinghang.wayofrich.common.*;
import com.sunfusheng.marqueeview.MarqueeView;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页
 */
public class IndexFragment extends Fragment {
    //启动页
    LinearLayout linearLayout;
    //银行列表
    private List<IndexBank> bankList;

    //文章列表
    private ArrayList<IndexArticle> articleList;
    public static Map<String, Bitmap> gridviewBitmapCaches = new HashMap<String, Bitmap>();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_index, container, false);
        //设置顶部bar栏
        new HeadBar().commonHeadBar(view);
        ImageView headImage = view.findViewById(R.id.headImage);
        headImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(getActivity(), BecomeVipActivity.class);
                startActivity(intent1);
            }
        });
        //跳转全部银行页面
        allBankTextEvent(view);

        //初始化跑马灯
        initNotice(view);

        //设置银行列表
        initBanks(view);

        //初始化文章列表
        initArticles(view);

        //邀请会员跳转
        ImageView inviteVip = view.findViewById(R.id.invite_vip);
        inviteVip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(getActivity(), InviteVipActivity.class);
                startActivity(intent1);
            }
        });
        //邀请办卡跳转
        ImageView inviteCard = view.findViewById(R.id.invite_card);
        inviteCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(getActivity(), InviteCardActivity.class);
                startActivity(intent1);
            }
        });

        return view;
    }

    /**
     * 文章列表
     */
    private void initArticles(final View view) {
        RequestQueue requestQueue = Volley.newRequestQueue(view.getContext());
        String url = UrlConstant.getReuqestUrl(UrlConstant.URL_GET_ARTICLES);
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("status", "1");//渠道状态（0-禁用 1-启用）
        hashMap.put("pageNum", "1");//頁碼
        hashMap.put("pageSize", "5");//每頁顯示數量
        hashMap.put("recommend", "1");//是否首页显示（0-否 1-是）
        CustomRequest jsonObjectRequest = new CustomRequest(Request.Method.POST,
                url, hashMap, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("获取文章结果", jsonObject.toString());
                ListView listView = view.findViewById(R.id.articleList);
                JSONArray banks = null;
                articleList = new ArrayList<IndexArticle>();
                try {
                    banks = jsonObject.getJSONObject("data").getJSONArray("rows");
                    for (int i = 0; i < banks.length(); i++) {
                        JSONObject article = banks.getJSONObject(i);
                        IndexArticle indexArticle = new IndexArticle();
                        indexArticle.setTitle(article.getString("title"));
                        indexArticle.setCreateTime(article.getString("createTime"));
                        indexArticle.setImgUrl(article.getString("headPic"));
                        articleList.add(indexArticle);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                IndexListAdapter adapter = new IndexListAdapter(articleList, getContext());
                listView.setAdapter(adapter);
                // 添加菜单点击
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                            long arg3) {
                        for (int i = 0; i < articleList.size(); i++) {
                            if (arg2 == i) {
//                                Toast.makeText(getContext(),
//                                        articleList.get(arg2).get("articleTitle") + "    " + arg2, Toast.LENGTH_SHORT)
//                                        .show();
                            }
                        }
                    }
                });
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("请求出错", volleyError.getMessage());
            }
        });
        requestQueue.add(jsonObjectRequest);

    }

    /**
     * 获取银行列表
     *
     * @param view
     */
    private void initBanks(final View view) {
        RequestQueue requestQueue = Volley.newRequestQueue(view.getContext());
        String url = UrlConstant.getReuqestUrl(UrlConstant.URL_GET_BANKS);
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("status", "1");//渠道状态（0-禁用 1-启用）
        hashMap.put("pageNum", "1");//頁碼
        hashMap.put("pageSize", "8");//每頁顯示數量
        hashMap.put("recommend", "1");//是否首页显示（0-否 1-是）
        CustomRequest jsonObjectRequest = new CustomRequest(Request.Method.POST,
                url, hashMap, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("获取银行结果", jsonObject.toString());
                GridView bankView = view.findViewById(R.id.indexBankList);
                JSONArray banks = null;
                bankList = new ArrayList<IndexBank>();
                try {
                    banks = jsonObject.getJSONObject("data").getJSONArray("rows");
                    for (int i = 0; i < banks.length(); i++) {
                        JSONObject bank = banks.getJSONObject(i);
                        IndexBank bankBo = new IndexBank();
                        bankBo.setName(bank.getString("shortBankName"));
                        bankBo.setImgurl(bank.getString("logoUrl"));
                        bankList.add(bankBo);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                IndexGridAdapter adapter = new IndexGridAdapter(bankList, getContext());
                bankView.setAdapter(adapter);
                bankView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                        Intent intent1 = new Intent(getActivity(), ApplyCardActivity.class);
                        startActivity(intent1);
                    }
                });
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("请求出错", volleyError.getMessage());
            }
        });
        requestQueue.add(jsonObjectRequest);

    }

    /**
     * 跑马灯初始化
     *
     * @param view
     */
    private void initNotice(final View view) {
        RequestQueue requestQueue = Volley.newRequestQueue(view.getContext());
        String url = UrlConstant.getReuqestUrl(UrlConstant.URL_GET_NOTICE);
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("pageSize", "10");

        CustomRequest jsonObjectRequest = new CustomRequest(Request.Method.POST,
                url, hashMap, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("请求结果", jsonObject.toString());
                MarqueeView marqueeView = (MarqueeView) view.findViewById(R.id.marqueeView);
                List<String> info = new ArrayList<>();
                try {
                    JSONArray result = jsonObject.getJSONArray("data");
                    for (int i = 0; i < result.length(); i++) {
                        info.add(result.get(i).toString());
                    }
                } catch (Exception e) {

                }
                marqueeView.startWithList(info);
                marqueeView.startWithList(info, R.anim.anim_bottom_in, R.anim.anim_top_out);
                marqueeView.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
                    @Override
                    public void onItemClick(int position, TextView textView) {

                    }
                });
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("请求出错", volleyError.getMessage());
            }
        });
        requestQueue.add(jsonObjectRequest);
    }

    private void allBankTextEvent(final View view){
        TextView allBank = view.findViewById(R.id.bank_all);
        allBank.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity.mBottomNavigationBar.selectTab(1);
            }
        });
    }
}
